<?php
class Application_Model_UserMapper
{
    protected $_dbTable;
    public function setDbTable ($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (! $dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }
    public function getDbTable ()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_User');
        }
        return $this->_dbTable;
    }
    /**
     * 
     * Save one instance of the Application_Model_User
     * @param Application_Model_User $user
     */
    public function save (Application_Model_User $user)
    {
        $data = array('UID' => $user->getUid(), 'Name' => $user->getName(), 
        'Password' => $user->getPassword(), 'VIP' => $user->getVIP());
        if (null === ($id = $user->getUid())) {
            unset($data['UID']);
            $this->getDbTable()->insert($data);
        } else {
            $this->getDbTable()->update($data, array('UID = ?' => $id));
        }
    }
    public function find ($id, Application_Model_User $user)
    {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();
        $user->setUid($row->UID)
            ->setName($row->Name)
            ->setPassword($row->Password)
            ->setVIP($row->VIP);
    }
    public function fetchAll ()
    {
        $resultSet = $this->getDbTable()->fetchAll();
        $entries = array();
        foreach ($resultSet as $row) {
            $entry = new Application_Model_Admin();
            $entry->setUid($row->UID)
                ->setName($row->Name)
                ->setPassword($row->Password)
                ->setVIP($row->VIP);
            $entries[] = $entry;
        }
        return $entries;
    }
    
    public function fetchByName ($column, $value)
    {
        $db = $this->getDbTable()->getAdapter();
        $where = $db->quoteInto($column . ' = ?', $value);
        $resultSet = $this->getDbTable()->fetchRow($where);
        $entries = array();
        foreach ($resultSet as $row) {
            $entry = new Application_Model_Admin();
            $entry->setUid($row->UID)
                ->setName($row->Name)
                ->setPassword($row->Password)
                ->setVIP($row->VIP);
            $entries[] = $entry;
        }
        return $entries;
    }
}

